﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Facebook;

namespace MishraReader.Services
{
    internal class FacebookApi : IFacebookApi
    {
        private static readonly Uri RedirectUri = new Uri("https://www.facebook.com/connect/login_success.html");

        public string AppId { get; set; }
        public string AppSecret { get; set; }

        public bool AdditionalInputRequired(Uri uri)
        {
            var str = uri.ToString();

            return str.Contains("&next=") || str.Contains("dialog");
        }

        public async Task<string> ExchangeCodeForAccessTokenAsync(string code,
                                                            CancellationToken cancellationToken =
                                                                default(CancellationToken))
        {
            var fb = new FacebookClient();
            var result = await fb.GetTaskAsync("oauth/access_token", new
            {
                client_id = AppId,
                client_secret = AppSecret,
                redirect_uri = RedirectUri.AbsoluteUri,
                code = code
            });
            
            var output = (IDictionary<string, object>)result;
            var accessToken = (string)output["access_token"];
            return accessToken;
        }

        public Uri GetLoginUrl(IDictionary<string, object> parameters)
        {
            var fb = new FacebookClient();

            parameters["redirect_uri"] = RedirectUri;
            parameters["client_id"] = AppId;

            return fb.GetLoginUrl(parameters);
        }

        public bool TryParseResult(Uri uri, out IFacebookResult result)
        {
            result = null;

            var fb = new FacebookClient();
            FacebookOAuthResult fbres;
            var parsed = fb.TryParseOAuthCallbackUrl(uri, out fbres);

            if (parsed)
            {
                result = new FacebookResult(fbres.IsSuccess, fbres.Code);
            }

            return parsed;
        }
    }

    internal class FacebookResult : IFacebookResult
    {
        public FacebookResult(bool isSuccess, string code)
        {
            IsSuccess = isSuccess;
            Code = code;
        }

        public string Code { get; private set; }
        public bool IsSuccess { get; private set; }
    }
}